package com.cy.pj.controller;

import com.cy.module.pojo.ResponseResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@RestController
public  class JsonController {

    @RequestMapping("/doConvertResponseToJson")
    @ResponseBody
    public ResponseResult doConvertResponseToJson(){
        ResponseResult rs=new ResponseResult();
        rs.setCode(200);
        rs.setMessage("OK");
        return rs;
    }

    @RequestMapping("/doConvertMapToJson")
    public Map<String,Object> doConvertMapToJson(){
        Map<String,Object> map=new HashMap<>();
        map.put("username","刘德华");
        map.put("state",true);
        return map;
    }

    @RequestMapping("/doPrintJSON")
    public void doPrint(HttpServletResponse response)throws Exception{
        Map<String,Object> map=new HashMap<>();
        map.put("username","刘德华");
        map.put("state",true);
        //将map中的数据转换为json格式字符串
        ObjectMapper om=new ObjectMapper();
        String jsonStr=om.writeValueAsString(map);
        System.out.println("jsonStr="+jsonStr);
        //将字符串响应到客户端
        //设置响应数据的编码
        response.setCharacterEncoding("utf-8");
        //告诉客户端,要向它响应的数据类型为text/html,编码为utf-8.请以这种编码进行数据呈现
        response.setContentType("text/html;charset=utf-8");
        PrintWriter pw=response.getWriter();
        pw.println(jsonStr);
    }

}